import { GIS_MAP_SECRET_KEY } from '../constant/index'
import axios from 'axios'
/**
 * 微服务生成uuid
 * @returns {string}
 */
export const getUUID = function () {
  var s = []
  var hexDigits = '0123456789abcdef'
  for (var i = 0; i < 36; i++) {
    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1)
  }

  s[14] = '4'
  s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1)
  s[8] = s[13] = s[18] = s[23] = '-'

  var uuid = s.join('')
  return uuid
}

/**
 * 封装axios，拦截器内对请求和相应进行预处理
 */
let CancelToken = axios.CancelToken
let pending = []
// 拦截多次请求同一事件
let removePending = (ever) => {
  for (let p in pending) {
    if (pending[p].u === ever.url) {
      pending[p].f()
      pending.splice(p, 1)
    }
  }
}

let service = axios.create({})

service.interceptors.request.use(
  (config) => {
    console.log('41', config)
    removePending(config) //在发送请求前执行取消操作
    config.cancelToken = new CancelToken((c) => {
      // 添加axios表示，为url
      pending.push({ u: config.url, f: c })
    })

    console.log('47', config)
    //设置服务校验的header相关参数
    let uid = getUUID()
    let accessToken =
      (config.params ? config.params.token : config.token) || window.token || ''
    let timestamp = new Date().getTime()
    let securityKey = GIS_MAP_SECRET_KEY // 此变量为微服务申请sn

    console.log('56', config)

    let signInfo =
      'timestamp=' + timestamp + '&random=' + uid + '&secretkey=' + securityKey
    if (accessToken) {
      signInfo = 'token=' + accessToken + '&' + signInfo
    }
    config.headers.common['token'] = accessToken
    config.headers.common['random'] = uid
    config.headers.common['timestamp'] = timestamp
    config.headers.common['sign'] = sm3(signInfo).toUpperCase()

    console.log('68', config)

    return config
  },
  (error) => {
    console.log('73', config)
    console.error('请求超时')
    return Promise.resolve(error)
  }
)

service.interceptors.response.use(
  (response) => {
    removePending(response.config) //在一个axios请求响应后在执行一次操作，把已经完成的请求从pending中移除；
    if (response && response.status === 200) {
      return response
    } else {
      reject({ message: '网络异常' })
      console.error('网络异常')
    }
  },
  (error) => {
    return Promise.reject(error)
  }
)

service.defaults.headers.post['Content-Type'] = 'application/json'
service.defaults.headers.post['X-Requested-With'] = 'XMLHttpRequest'

export const get = function (url, param = {}) {
  return new Promise((resolve, reject) => {
    service({
      method: 'get',
      url,
      params: param,
    })
      .then((res) => {
        if (res.data.success == true && res.data.resultValue) {
          resolve(res)
        } else {
          console.log('something error')
          console.error(res.data.message)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}

function getTile(url, param = {}) {
  return new Promise((resolve, reject) => {
    service({
      method: 'get',
      url: url,
      params: param,
      responseType: 'blob',
    })
      .then((res) => {
        resolve(res)
      })
      .catch((err) => {
        reject(err)
      })
  })
}

export const post = function (url, param = {}) {
  return new Promise((resolve, reject) => {
    service({
      method: 'post',
      url,
      data: param,
    })
      .then((res) => {
        console.log('post-------', res)
        if (res.data.success == true && res.data.resultValue) {
          resolve(res)
        } else {
          console.log('something error')
          console.error(res.data.message)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}
